package kjx_test_security.filter;


import com.alibaba.fastjson.JSONObject;
import kjx_test_security.auth.ExampleUser;
import kjx_test_security.auth.entity.KcAuthUserModel;
import kjx_test_security.tools.Result;
import kjx_test_security.tools.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @Author 康1919
 * @Date 2024/7/20 14:04
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getParameter("token");
        System.out.println("---------------------------");
        System.out.println(token);
        System.out.println("---------------------------");
        System.out.println("---------------------------");
        // 如果不存在先放行 后面过滤器会自动识别是否是认证状态
        if(StringUtils.hasText(token)){
            KcAuthUserModel loginUser = ExampleUser.getExampleUser(true);

            // 存入SecurityContextHolder
            //TODO 获取权限信息封装到Authentication中
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }


        // 放行
        filterChain.doFilter(request, response);


    }
}